package com.woniu.market_stall_web.intercepters;

import com.woniu.market_stall_web.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PermissionIntercepter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        User user = (User) request.getSession().getAttribute("userInfo");
        String header = request.getHeader("X-Requested-With");
        if (user == null) {
            if (uri.contains("checkName")) {
                return true;
            } else if ("XMLHttpRequest".equals(header)) {
                //判断是ajax请求 还是 同步请求  如果是ajax请求 请求头中 会多一个请求头
                //名称 ：X-Requested-With  值 ：XMLHttpRequest
                //ajax请求
                response.getWriter().print("ajax");
            } else {
                request.setAttribute("errorInfo", "请先登录!");
                request.getRequestDispatcher("/login.html").forward(request, response);
            }
            return false;
        }
        return true;
    }
}
